package com.ckd.flyingtrip.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.utils.DownloadUtils;


/**
 * 更新APP
 * Created by HITMAN on 2018/7/2.
 */
public class UPDATEAPP extends Dialog {
    private Activity context;
    private TextView tnum;
    private ProgressBar progressBar;
    private String ver,url;
    private Button btn_res;
    public UPDATEAPP(Activity context,String ver,String url) {
        super(context, R.style.no_border_dialog);
        this.context=context;
        this.ver=ver;
        this.url=url;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Window window = this.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.updateapp);
        TextView txt_info = (TextView) findViewById(R.id.txt_info);
        txt_info.setText(ver);
        window.getDecorView().setPadding(0, 0, 0, 0);
        setCanceledOnTouchOutside(false);
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
            {
                if (keyCode == KeyEvent.KEYCODE_SEARCH)
                {
                    return true;
                }
                else
                {
                    return true; //默认返回 false，这里false不能屏蔽返回键，改成true就可以了
                }
            }
        });
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //设置dialog的位置在中间
        lp.gravity = Gravity.CENTER;
        getWindow().setAttributes(lp);
        init();
    }

    Handler handler=new Handler();
    private void init() {
        // 产生背景变暗效果
        WindowManager.LayoutParams lp = context.getWindow()
                .getAttributes();
        lp.alpha = 0.7f;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                WindowManager.LayoutParams lp = context.getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                context.getWindow().setAttributes(lp);
            }

        });

        tnum = (TextView) this.findViewById(R.id.tnum);
        btn_res = (Button) this.findViewById(R.id.btn_res);
        progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
        findViewById(R.id.btn_res).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("app下载路径",url);
//                "http://www.51hg.co/app-armeabi-v7a-release-01.apk"
                new DownloadUtils(context, url, "飞哥出行.apk");
                handler.postDelayed(runnable, 1000);
                btn_res.setEnabled(false);
                btn_res.setBackgroundColor(context.getResources().getColor(R.color.common_deepgray));
                btn_res.setText("正在升级中");
            }
        });


    }


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 500);
            int downloadPercent = getDownloadPercent(DownloadUtils.downloadId);
            System.out.println("进度:"+downloadPercent);
            progressBar.setProgress(downloadPercent);
            tnum.setText(downloadPercent+"%");
            if(downloadPercent==100){
                handler.removeCallbacks(runnable);
//                dismiss();
            }

        }
    };

    private int getDownloadPercent(long downloadId){
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c =  DownloadUtils.downloadManager.query(query);
        if(c.moveToFirst()){
            int downloadBytesIdx = c.getColumnIndexOrThrow(
                    DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            int totalBytesIdx = c.getColumnIndexOrThrow(
                    DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            long totalBytes = c.getLong(totalBytesIdx);
            long downloadBytes = c.getLong(downloadBytesIdx);
            return (int) (downloadBytes * 100 / totalBytes);
        }
        return 0;
    }


}